package api

import (
	"encoding/json"
	"fmt"
	"strconv"
	"zinx_websokect_poker/zinx/ziface"
	"zinx_websokect_poker/zinx/znet"
	"zinx_websokect_poker/zinx_app/poker_game/core"
	"zinx_websokect_poker/zinx_app/poker_game/http"
	json2 "zinx_websokect_poker/zinx_app/poker_game/json"
	"zinx_websokect_poker/zinx_app/poker_game/log"
)

type LoginApi struct {
	znet.BaseRouter
}

func (*LoginApi) Handle(request ziface.IRequest) {
	//TODO 用户连接，接受用户token，访问后台接口，登录失败则断开连接
	request.GetConnection().GetProperty("Pid")

}

type BindInfoApi struct {
	znet.BaseRouter
}

type bindInfoMsg struct {
	Cmd interface{}	 `json:"cmd"`
	Msg *BindInfo	 `json:"msg"`
}

type BindInfo struct {
	Name string `json:"name"`
	OutID int64 `json:"outId"`
	Mobile string `json:"mobile"`
	Avatar string `json:"avatar"`
}

func (*BindInfoApi) Handle(request ziface.IRequest) {
	conn := request.GetConnection()
	p, _ := conn.GetProperty("Pid")
	pid := p.(uint32)
	o := core.OccupantMgrObj.GetOccupantByPid(pid)

	if o == nil{
		log.Error("Login-BindInfo", "connId:" + strconv.Itoa(int(conn.GetConnID())) +
			"找不到链接绑定的Occupant，无法绑定玩家信息！")
		return
	}

	out,_ := conn.GetProperty("OutId")
	//链接已绑定信息，不作处理
	if out != nil{
		log.Info("Login-BindInfo", "connId:" + strconv.Itoa(int(conn.GetConnID())) +
			" 链接已绑定信息，不作处理")
		return
	}

	jr :=  bindInfoMsg{}
	data := request.GetData()
	err := json.Unmarshal(data,&jr)

	if err != nil {
		fmt.Println(err)
	}

	//
	checkLogin(jr.Msg.OutID)

	//主要用于重连回复。
	reloadStu := json2.Jsonmr(8,nil)
	o.WriteMsg(reloadStu)

	fmt.Println("处理玩家信息")
	o.Nickname = jr.Msg.Name
	o.Mobile = jr.Msg.Mobile
	o.OutId = jr.Msg.OutID
	o.Profile = jr.Msg.Avatar
	conn.SetProperty("OutId", o.OutId)

	log.Info("Login-BindInfo", "连接初始化用户信息, connId:" + strconv.Itoa(int(conn.GetConnID())) +
		",用户昵称：" + o.Nickname+ "OutId:"+ strconv.Itoa(int(o.OutId)))

	// todo 通过OutID获取玩家的房间号，如果有则触发加入房间的操作。
	m := http.GetUserGameId(jr.Msg.OutID)
	if len(m["roomId"]) > 0{
		//获取到房间号且玩家当前无绑定房间，房间存在，进行重连操作
		r := core.GetRoom(m["roomId"])
		if o.GetRoom() == nil && r != nil{
			// todo JoinRoom
			fmt.Println("获取到房间号且玩家当前无绑定房间，进行重连操作")
			fmt.Println(m["roomId"])
			r.ReJoinRoom(o, 0)
		}
	}
}

//玩家重复登录响应
func checkLogin(outId int64){
	Players := core.PlayerMgrObj.GetAllPlayers()

	for _, player := range Players {
		if player.OutId == outId {
			log.Info("Login-CheckLogin","用户重复登录，OID为"+strconv.Itoa(int(player.OutId))+",用户昵称:"+player.Nickname)
			js := json2.Jsonmr(7,"当前账号已在其他地方登录!")
			player.Conn.WriteMessage(js)
			//关闭链接
			player.Conn.Stop()
			break
		}
	}

}